﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Mapa.Master" 
    Inherits="System.Web.Mvc.ViewPage<zeus.Core.Poligono>" %>
    <%@ Import Namespace="zeus.Web.Controllers" %>
<%@ Import Namespace="Webdiyer.WebControls.Mvc" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"> 
   
    <img src="http://google.com/mapfiles/ms/t/Bsd.png" id="hand" />
    <img src="http://google.com/mapfiles/ms/t/Blu.png" id="shape" />
    
    <a href="<%= ResolveUrl("~") %>Recursos/Rutas">Regresar</a>

    <table id ="featuretable">
        <tbody id="featuretbody"></tbody>
    </table>
    <div id="map" style="width: 100%; height: 100%;">
    </div>    
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="HeadContentPlaceHolder" runat="server">
    <script type="text/javascript" src="<%= ResolveUrl("~") %>Content/Mapa/dragzoom.js" ></script>
    <script type="text/javascript">
        var permitirEditar = true;
        var points = new Array();
        var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green", "#008000"], ["blue", "#000080"], ["purple", "#800080"]];
        var options = {};
        var colorIndex_ = 0;
        var featureTable_;
        var map;
        var zoom;
        var latCenter;
        var lngCenter;

        $(function () {
            $("#hand").bind("click", function () {
                stopEditing();
            });

            $("#shape").bind("click", function () {
                startLine();
            });            
        });

        function savePoints(points) {
            $.ajax({
                type: "POST",
                url: "<%= ResolveUrl("~") %>Recursos/SavePoints",
                data: "id=<%: Model.Id %>&ptos=" + points + "&zoom=" + getZoom() + "&lat=" + getLatCenter() + "&lng=" + getLngCenter(),
                dataType: "json",
                cache: false,
                success: function (response) {
                   
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.responseText);
                }
            });
        }
        
        function retrievePoints() {
            $.ajax({
                type: "POST",
                url: "<%= ResolveUrl("~") %>Recursos/RetrievePoints",
                data: "id=<%: Model.Id %>",
                dataType: "json",
                async: false,
                cache: false,
                success: function (response) {
                   $.each(response, function(i, data) {
                       var p = new GLatLng(data.Latitud, data.Longitud);
                       zoom = data.Zoom;
                       latCenter = data.LatCenter;
                       lngCenter = data.LngCenter;
                       points.push(p);
                   });
                   
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.responseText);
                }
            });
        }
        
        function stopEditing() {
            $("#hand").attr("src", "http://google.com/mapfiles/ms/t/Bsd.png");
            $("#shape").attr("src", "http://google.com/mapfiles/ms/t/Blu.png");
        }

        function startLine() {
            if (permitirEditar == false) {
                alert("Sólo se puede crear un perímetro");
                return
            }
            $("#hand").attr("src", "http://google.com/mapfiles/ms/t/Bsu.png");
            $("#shape").attr("src", "http://google.com/mapfiles/ms/t/Bld.png");

            var color = getColor(false);
            var line = new GPolyline(points, color);

            startDrawing(line, "", function() {
                var cell = this;
                var len = line.getLength();
                                                
                var puntos = line.getVertexCount();
                var ubicacion = new Array();
                var i = 0;

                for (i = 0; i < puntos; i++) {
                    ubicacion.push(line.getVertex(i));                    
                }

                savePoints(ubicacion);
                cell.innerHTML = "Datos actualizados: " + (Math.round(len / 10) / 100) + "km";
            }, color);
        }
                
        function getColor(named) {
            return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
        }
                                
        function addFeatureEntry(name, color) {
            currentRow_ = document.createElement("tr");
            var colorCell = document.createElement("td");
            currentRow_.appendChild(colorCell);
            colorCell.style.backgroundColor = color;
            colorCell.style.width = "1em";
            var nameCell = document.createElement("td");
            currentRow_.appendChild(nameCell);
            nameCell.innerHTML = name;
            var descriptionCell = document.createElement("td");
            currentRow_.appendChild(descriptionCell);
            featureTable_.appendChild(currentRow_);                
            return { desc: descriptionCell, color: colorCell };
        }

        function startDrawing(poly, name, onUpdate, color) {
            map.addOverlay(poly);
            poly.enableDrawing(options);
            poly.enableEditing({ onEvent: "mouseover" });
            poly.disableEditing({ onEvent: "mouseout" });
            GEvent.addListener(poly, "endline", function () {
                stopEditing();
                
                var puntos = poly.getVertexCount();
                var ubicacion = new Array();
                var i = 0;

                for (i = 0; i < puntos; i++) {
                    ubicacion.push(poly.getVertex(i));                    
                }

                savePoints(ubicacion);
                permitirEditar = false;

                var cells = addFeatureEntry(name, color);
                
                GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
                GEvent.addListener(poly, "click", function (latlng, index) {
                    if (typeof index == "number") {
                        poly.deleteVertex(index);
                    } else {
                        var newColor = getColor(false);
                        cells.color.style.backgroundColor = newColor
                        poly.setStrokeStyle({ color: newColor, weight: 4 });
                    }
                });
            });
        }
                
        function initialize() {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById("map"));

                if( points.length > 0 )
                    map.setCenter(new GLatLng(latCenter, lngCenter), zoom);
                else
                    map.setCenter(new GLatLng(-0.201015, -78.493537), 6);

                // map.addControl(new GLargeMapControl());
                map.setUIToDefault();
                map.enableRotation();
                map.addControl(new GMapTypeControl());
                 map.addMapType(G_SATELLITE_3D_MAP);
                         map.addControl(new DragZoomControl());
                map.clearOverlays();
                featureTable_ = document.getElementById("featuretbody");
            }
        }

        $(window).load(function () {
            retrievePoints();  
            initialize();
                        
            if(points.length > 0)
            {
                var color = getColor(false);
                var line = new GPolyline(points, color);
                map.addOverlay(line);                
            }
        });

        function getZoom()
        {
            return map.getZoom();
        }

        function getLatCenter()
        {
            return map.getCenter().lat();
        }

        function getLngCenter()
        {
            return map.getCenter().lng();
        }

        $(window).unload(function () {
            GUnload();
        });
    </script>
</asp:Content>
